package gcontent.channel;

import java.util.HashMap;

import gcontent.rsrc.ThreadResources;
import gcontent.channel.error.ChannelEx;
import gcontent.entities.Site;

public class ChannelManager {
	
	private static HashMap<String, Class<?>> channel_list = new HashMap<String, Class<?>>();

	static {
		try { 
			init();
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private static void init() throws ChannelEx
	{
		ChannelManager.registerChannel(gcontent.channel.http.ChannelHTTP.TYPE_HTTP, gcontent.channel.http.ChannelHTTP.class);
		ChannelManager.registerChannel(gcontent.channel.http.ChannelHTTP.TYPE_HTTPS, gcontent.channel.http.ChannelHTTP.class);
		
		ChannelManager.registerChannel(gcontent.channel.ftp.ChannelFTP.TYPE_FTP, gcontent.channel.ftp.ChannelFTP.class);				
		ChannelManager.registerChannel(gcontent.channel.dns.ChannelDNS.TYPE_DNS, gcontent.channel.dns.ChannelDNS.class);
	}
	
	/* get a channel class from url protocol */
	public static Channel getChannel(String protocol) throws ChannelEx
	{
		Class<?> cls;
		Channel channel;
		HashMap<String, Channel> channel_ins;
		
		channel_ins = (HashMap<String, Channel>)ThreadResources.getResource(ThreadResources.RSRC.CHANNEL_INS);
		if(channel_ins == null) {
			channel_ins = new HashMap<String, Channel>();
			channel = null;
			
			ThreadResources.registerResource(ThreadResources.RSRC.CHANNEL_INS, channel_ins);
		} else 
			channel = channel_ins.get(protocol.toUpperCase());
		
		if(channel != null)
			return channel;
	
		cls = channel_list.get(protocol.toUpperCase());		
		/* channel type not registered?*/
		if(cls == null)
			return null;
		
		try { 
			/* instance channel object */
			channel = (Channel)cls.newInstance();
			
			/* remember instance */
			channel_ins.put(protocol.toUpperCase(), channel);
			
		} catch(Exception ex) {
			throw new ChannelEx(ex);
		}

		return channel;
	}

	/* get a channel class from url protocol */
	public static Channel getChannel(Site site) throws ChannelEx
	{
		return getChannel(site.getProtocol());
	}
	
	/* register a channel class */
	public static void registerChannel(String proto, Class<?> channel) throws ChannelEx
	{
		if(channel_list.get(proto) != null)
			throw new ChannelEx("channel already was registed (" + channel + ")");
		
		channel_list.put(proto, channel);
	}
}